package jnu.se.softwareengineer3306.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnu.se.softwareengineer3306.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: LovEK
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserService userService;
    @Autowired
    UserDetailServiceImpl(UserService userService){
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = new ArrayList<>();

        // 通过用户名取得用户
        QueryWrapper<jnu.se.softwareengineer3306.pojo.User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        jnu.se.softwareengineer3306.pojo.User user = userService.getOne(wrapper);

        if (user == null || !user.getUsername().equals(username)){
            throw new UsernameNotFoundException("用户名不存在不存在或密码错误");
        }

        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}
